﻿using System.Linq;

using Sustainalytics.Portfolios.BL.Model;

namespace Sustainalytics.Universes.Synchronization
{
    public class SystemPortfolioManager : ISystemPortfolioManager
    {
        private readonly IUniverseInfo _universeInfo;

        public SystemPortfolioManager(IUniverseInfo universeInfo)
        {
            _universeInfo = universeInfo;
        }

        public SystemPortfolioInfo[] CreateSystemPortfolios()
        {
            var standardPortfolioCompanies = (
                from account in _universeInfo.AccountSet
                join accountUniverse in _universeInfo.AccountUniverseSet on account.Id equals accountUniverse.AccountRef.Id
                join compGroupAccUnivBridge in _universeInfo.CompaniesGroupAccountUniverseBridgeSet on accountUniverse.Id equals compGroupAccUnivBridge.AccountUniverseId
                join companiesGroup in _universeInfo.CompaniesGroupSet on compGroupAccUnivBridge.CompaniesGroupId equals companiesGroup.Id
                join referenceUniverse in _universeInfo.ReferenceUniverseSet on companiesGroup.Name equals referenceUniverse.Name
                where companiesGroup.IsStandard != null && companiesGroup.IsStandard.Value == true
                from company in referenceUniverse.Companies
                select new 
                {
                    AccountId = account.Id, 
                    Name = companiesGroup.Name,
                    Id = companiesGroup.Id,
                    CompanyId = company.CompanyId,
                    CreatedOn = companiesGroup.CreatedOn,
                    ModifiedOn = companiesGroup.ModifiedOn
                }).Distinct();

            return
                standardPortfolioCompanies
                    .GroupBy(
                        x => new { x.Name, x.Id, x.ModifiedOn, x.CreatedOn },
                        (key, g) => new
                                        {
                                            Name = key.Name,
                                            Id = key.Id,
                                            ModifiedOn = key.ModifiedOn,
                                            CreatedOn = key.CreatedOn,
                                            Accounts = g.Select(x => x.AccountId).Distinct().ToArray(),
                                            Companies = g.Select(x => x.CompanyId).Distinct().ToArray()
                                        })
                    .Select(
                        x =>
                        new SystemPortfolioInfo()
                            {
                                Id = x.Id,
                                Name = x.Name,
                                AccountIds = x.Accounts,
                                CompanyIds = x.Companies,
                                DateModified = x.ModifiedOn,
                                DateCreated = x.CreatedOn
                            })
                    .ToArray();
        }
    }
}
